package com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser;

import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser.handler.TenantColumnHandler;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.SubSelect;

/**
 * Created by Administrator on 2019/12/23.
 * 租户共享表,以tenantId字段隔离数据
 */
public class TenantColumnSqlParser extends TenantSqlParser{

    @Override
    protected Expression builderExpression(Expression expression, Table table) {
        TenantColumnHandler tenantHandler = (TenantColumnHandler)this.getTenantHandler();
        Expression tenantExpression = tenantHandler.getTenantId(true);
        if(tenantExpression==null){
            return expression;
        }
        Expression appendExpression;
        if(!(tenantExpression instanceof OldOracleJoinBinaryExpression)){
            appendExpression = new EqualsTo();
            ((EqualsTo)appendExpression).setLeftExpression(this.getAliasColumn(table));
            ((EqualsTo)appendExpression).setRightExpression(tenantExpression);
        }else {
            appendExpression = tenantExpression;
        }
        if(expression==null){
            return appendExpression;
        }else {
            if(expression instanceof BinaryExpression) {
                BinaryExpression binaryExpression = (BinaryExpression)expression;
                if(binaryExpression.getLeftExpression() instanceof FromItem) {
                    this.processFromItem((FromItem)binaryExpression.getLeftExpression());
                }

                if(binaryExpression.getRightExpression() instanceof FromItem) {
                    this.processFromItem((FromItem)binaryExpression.getRightExpression());
                }
            }
            else if(expression instanceof InExpression){
                InExpression inExpression = (InExpression)expression;
                ItemsList rightItems = inExpression.getRightItemsList();
                if(rightItems instanceof SubSelect){
                    this.processSelectBody(((SubSelect)rightItems).getSelectBody());
                }
            }

            if(expression instanceof OrExpression){
                return new AndExpression(new Parenthesis(expression),appendExpression);
            }else {
                return new AndExpression(expression,appendExpression);
            }
        }
    }
}
